﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
//using Microsoft.SharePoint.WebPartPages;
using IntelligentDecisioning.SharePoint.Logging;
using System.Xml;
using System.IO;
using UIWebPart = System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;

namespace IntelligentDecisioning.SharePoint.Actions
{
    public class ProvisionWebPartAction: IPageAction
    {
        /// <summary>
        /// The name of an existing webpart in the webpart gallery
        /// </summary>
        public String WebPartName { get; set; }

        /// <summary>
        /// The .webpart xml definition of the webpart to add
        /// </summary>
        public String WebPartDefinition { get; set; }

        public String Title { get; set; }
        
        /// <summary>
        /// The name of the webpart zone to add the webpart to
        /// </summary>
        public String WebPartZoneId { get; set; }

        /// <summary>
        /// The index for the webpart in the target zone
        /// </summary>
        public int Index { get; set; }

       
        #region IPageAction Members

        public void Provision(SPFile page, SPWeb currentWeb, SPSite currentSite, Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager wpm, ILog installationLog)
        {
            string errorMessage = String.Empty;
            UIWebPart.WebPart webPart = null;

            if (String.IsNullOrEmpty(WebPartDefinition) == false)
            {
                XmlReader xr = XmlReader.Create(new StringReader(WebPartDefinition));
                webPart = (UIWebPart.WebPart)wpm.ImportWebPart(xr, out errorMessage);
            }
            else
            {
                string url = currentSite.RootWeb.Url + "/_catalogs/wp/" + WebPartName;
                XmlTextReader reader = new XmlTextReader(new StringReader(currentSite.RootWeb.GetFileAsString(url)));
                webPart = (UIWebPart.WebPart)wpm.ImportWebPart(reader, out errorMessage);
            }
            
            wpm.AddWebPart(webPart, WebPartZoneId, Index);
        }

        #endregion
    }
}
